package com.tool.service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;

@Component
public class MessageProducer {

	@Autowired(required = false)
	private JmsTemplate jmsMailTemplate;

	@Autowired(required = false)
	private JmsTemplate jmsSMTemplate;	

	public void sendEmail(String toAddress, String title, String content, String fromName) {
		StringBuilder sb = new StringBuilder(2000);
		sb.append(toAddress);
		sb.append("##");
		sb.append(title);
		sb.append("##");
		sb.append(content);
		sb.append("##");
		sb.append(fromName);
		try {
			generateMessages(sb.toString(), 1);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	public void sendSM(String mobile, String content) {
		StringBuilder sb = new StringBuilder(150);
		sb.append(mobile);
		sb.append("##");
		sb.append(content);
		try {
			this.generateMessages(sb.toString(), 2);
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}

	private void generateMessages(final String msg, int type) throws JMSException {
		JmsTemplate template = null;
		if (type == 1)
			template = jmsMailTemplate;
		else
			template = jmsSMTemplate;
		template.send(new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				ObjectMessage message = session.createObjectMessage();
				Logger logger = Logger.getLogger(String.class);
				logger.setLevel(Level.ALL);
				LoggingEvent event = new LoggingEvent("", logger, logger.getLevel(), msg, new Throwable());
				message.setObject(event);
				return message;
			}
		});
	}

	public void setJmsMailTemplate(JmsTemplate jmsMailTemplate) {
		this.jmsMailTemplate = jmsMailTemplate;
	}

	public void setJmsSMTemplate(JmsTemplate jmsSMTemplate) {
		this.jmsSMTemplate = jmsSMTemplate;
	}	
}
